import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { getAuthToken, clearLoginStatus } from '../utils/auth'
import { getCurrentApiConfig } from '../config/env'

// 获取当前API配置
const apiConfig = getCurrentApiConfig()

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: apiConfig.baseURL, // 使用配置的baseURL
  timeout: apiConfig.timeout, // 使用配置的超时时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 自动添加token
api.interceptors.request.use(
  (config) => {
    const token = getAuthToken()
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 添加请求日志
    if (config.params) {
      console.log('📝 请求参数:', config.params)
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理token过期
api.interceptors.response.use(
  (response: AxiosResponse) => {
    // 添加响应日志
    return response
  },
  (error) => {
    
    if (error.response?.status === 401) {
      // Token过期或无效，清除登录状态
      clearLoginStatus()
      // 可以在这里添加重定向到登录页的逻辑
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 通用请求方法
export const request = {
  get: <T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T> => {
    return api.get(url, config)
  },
  
  post: <T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> => {
    return api.post(url, data, config)
  },
  
  put: <T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> => {
    return api.put(url, data, config)
  },
  
  delete: <T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T> => {
    return api.delete(url, config)
  }
}

// 登录API
export const loginAPI = async (credentials: { username: string; password: string }) => {
  const response = await request.post('/api/login', credentials)
  return response
}

// 获取用户信息API
export const getUserInfoAPI = async () => {
  const response = await request.get('/api/user/info')
  return response
}

// 更新用户信息API
export const updateUserInfoAPI = async (userData: unknown) => {
  const response = await request.put('/api/user/info', userData)
  return response
}

// 搜索API
export const searchAPI = async (searchParams: {
  pageCode: number
  pageSize: number
  searchValue: string
}) => {
  const response = await request.get('/search', { params: searchParams })
  return response
}



// 搜索科室API
export const searchDepartmentAPI = async (searchParams: {
  pageCode: number
  pageSize: number
  searchValue: string
}) => {
  console.log('🔍 搜索科室API调用:', searchParams)
  console.log('🌐 API基础URL:', api.defaults.baseURL)
  
  // 获取认证token
  const token = getAuthToken()
  console.log('🔑 认证token:', token ? '已设置' : '未设置')
  
  try {
    console.log(`🔗 请求路径: ${api.defaults.baseURL}/search/department`)
    
    // 添加认证头
    const config = {
      params: searchParams,
      headers: token ? { Authorization: `Bearer ${token}` } : {}
    }
    
    const response = await request.get('/search/department', config)
    console.log('✅ 搜索科室API成功:', response)
    console.log('📊 响应数据结构:', typeof response)
    console.log('📋 响应内容:', response)
    
    // 检查响应数据结构
    if (response && typeof response === 'object') {
      console.log('🔍 响应对象键:', Object.keys(response))
      if ('data' in response) {
        console.log('📋 响应data字段:', response.data)
      }
    }
    
    return response
  } catch (error) {
    console.error('❌ 搜索科室API错误:', error)
    console.error('🚨 错误详情:', {
      message: error instanceof Error ? error.message : '未知错误'
    })
    if (error && typeof error === 'object' && 'response' in error) {
      const axiosError = error as { response?: { status?: number; data?: unknown } }
      console.error('📡 HTTP状态:', axiosError.response?.status)
      console.error('📋 响应数据:', axiosError.response?.data)
    }
    throw error
  }
}

// 测试API连接
export const testApiConnection = async () => {
  try {
    console.log('🧪 测试API连接...')
    console.log('🌐 基础URL:', api.defaults.baseURL)
    
    // 测试一个更合理的路径，而不是根路径
    const testPaths = ['/api/health', '/health', '/status', '/ping']
    
    for (const path of testPaths) {
      try {
        console.log(`🔗 测试路径: ${path}`)
        const response = await request.get(path)
        console.log(`✅ 路径 ${path} 连接成功:`, response)
        return true
      } catch (error) {
        console.log(`❌ 路径 ${path} 失败:`, error instanceof Error ? error.message : '未知错误')
        // 继续尝试下一个路径
      }
    }
    
    // 如果所有路径都失败，尝试搜索接口
    console.log('🔗 尝试搜索接口...')
    const response = await request.get('/search', { params: { pageCode: 1, pageSize: 1, searchValue: 'test' } })
    console.log('✅ 搜索接口连接成功:', response)
    return true
    
  } catch (error) {
    console.error('❌ API连接失败:', error)
    return false
  }
}

export default api
